package com.luck.dto;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;

@Slf4j
@RestController
@RequestMapping("/api/sentinel2")
public class SentinelController2 {
    @GetMapping
    @SentinelResource(value = "order2",fallbackClass = SentinelController2.class,fallback = "fallHandler")
    public String test(int id) {
        if (id == 1){
            int i=5/0;
        }
        log.debug("下单成功");
        return "下单成功";
    }
    public static String fallHandler(int id) {
        log.debug("降级");
        return "降级";
    }

    @PostConstruct
    private void init() {
        ArrayList<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule();
        rule.setResource("order2");
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
        rule.setCount(2);
        rule.setTimeWindow(10);
        rule.setMinRequestAmount(10);
        rule.setStatIntervalMs(1000*10);
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);

    }
}
